/*
 * Copyright (C) 2015 wxcx Inc. All rights reserved.
 */
package net.soulwolf.test.poidemo;

import android.content.res.AssetManager;

import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.converter.PicturesManager;
import org.apache.poi.hwpf.converter.WordToHtmlConverter;
import org.apache.poi.hwpf.usermodel.Picture;
import org.apache.poi.hwpf.usermodel.PictureType;
import org.w3c.dom.Document;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;

import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * author: Ewen
 * since : 15/11/16 上午10:42.
 */
public class BaseApi {

    @SuppressWarnings("unused")
    private static final boolean DEBUG = true;
    @SuppressWarnings("unused")
    private static final String LOG_TAG = "BaseApi:";


    private BaseApi(){
    }

    public static Observable<File> wordConvert(final String fileName,final AssetManager assetManager,final String saveDir){
        return Observable.create(new Observable.OnSubscribe<File>() {
            @Override
            public void call(Subscriber<? super File> subscriber) {
                try{
                    subscriber.onStart();
                    String name = fileName.substring(0,fileName.indexOf("."));
                    File savePath = new File(saveDir,name + ".html");
                    convert2Html(assetManager.open(fileName),savePath);
                    subscriber.onNext(savePath);
                }catch (Exception e){
                    subscriber.onError(e);
                }
            }
        }).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread());
    }

    /**
     * word文档转成html格式
     * */
    private static void convert2Html(InputStream file, File savePath)
            throws TransformerException, IOException,
            ParserConfigurationException {
        final String docName = savePath.getName();

        HWPFDocument wordDocument = new HWPFDocument(file);
        WordToHtmlConverter wordToHtmlConverter = new WordToHtmlConverter(
                DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument());

        //设置图片路径
        wordToHtmlConverter.setPicturesManager(new PicturesManager()
        {
            public String savePicture( byte[] content,
                                       PictureType pictureType, String suggestedName,
                                       float widthInches, float heightInches )
            {
                String name = docName.substring(0,docName.indexOf("."));
                return name+"/"+suggestedName;
            }
        } );

        //保存图片
        List<Picture> pics=wordDocument.getPicturesTable().getAllPictures();
        if(pics!=null){
            for(int i=0;i<pics.size();i++){
                Picture pic = pics.get(i);
                System.out.println( pic.suggestFullFileName());
                try {
                    String name = docName.substring(0,docName.indexOf("."));
                    pic.writeImageContent(new FileOutputStream(new File(savePath.getParent() + "/" + name,pic.suggestFullFileName())));
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                }
            }
        }
        wordToHtmlConverter.processDocument(wordDocument);
        Document htmlDocument = wordToHtmlConverter.getDocument();
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        DOMSource domSource = new DOMSource(htmlDocument);
        StreamResult streamResult = new StreamResult(out);

        TransformerFactory tf = TransformerFactory.newInstance();
        Transformer serializer = tf.newTransformer();
        serializer.setOutputProperty(OutputKeys.ENCODING, "utf-8");
        serializer.setOutputProperty(OutputKeys.INDENT, "yes");
        serializer.setOutputProperty(OutputKeys.METHOD, "html");
        serializer.transform(domSource, streamResult);
        out.close();
        //保存html文件
        FileUtils.writeFile(new String(out.toByteArray()), savePath);
    }
}
